//
//  GPSViewController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/4/2.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "GPSViewController.h"
#import "MapLocation.h"

@interface GPSViewController ()

@property (retain, nonatomic) MKMapView *mapView;
@property (retain, nonatomic) UIActivityIndicatorView *activity;

@end

@implementation GPSViewController

@synthesize locationmanager,geocoder;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //初始化地图视图
    _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    //地图的代理方法
    _mapView.delegate = self;
    //是否显示当前的位置
    _mapView.showsUserLocation = YES;
    //地图的类型， iOS开发中自带的地图
    //使用第三方的地图可以查找周边环境的餐馆，学校之类的
    /*
     MKMapTypeStandard 标准地图
     MKMapTypeSatellite 卫星地图
     MKMapTypeHybrid 混合地图
     */
    _mapView.mapType = MKMapTypeStandard;
    
    
    
    
    //河南南阳的经纬度，初始化的坐标
    CLLocationCoordinate2D coor2d = {31.7,112.4};
    //显示范围，数值越大，范围就越大
    MKCoordinateSpan span = {10,10};
    MKCoordinateRegion region = {coor2d,span};
    //是否允许缩放，一般都会让缩放的
    //mapview.zoomEnabled = NO;
    //mapview.scrollEnabled = NO;
    //地图初始化时显示的区域
    [_mapView setRegion:region];
    [self.view addSubview:_mapView];
    locationmanager = [[CLLocationManager alloc]init];
    
    //设置精度
    /*
     kCLLocationAccuracyBest
     kCLLocationAccuracyNearestTenMeters
     kCLLocationAccuracyHundredMeters
     kCLLocationAccuracyHundredMeters
     kCLLocationAccuracyKilometer
     kCLLocationAccuracyThreeKilometers
     */
    //设置定位的精度
    [locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];
    //实现协议
//    通过locationmanager.delegate = self;是将委托对象指定为自身。因此，点击事件发生时候将会回调CLLocationManagerDelegate委托的
//     -locationManager:didUpdateToLocation:fromLocation:方法。
//    locationmanager.delegate = self;
    NSLog(@"开始定位");
    //开始定位
    [locationmanager startUpdatingLocation];
}


#pragma mark locationManager delegate

//实现定位 6.0 过期的做法
//- (void)locationManager:(CLLocationManager *)manager
//    didUpdateToLocation:(CLLocation *)newLocation
//           fromLocation:(CLLocation *)oldLocation
//{
//    NSLog(@"hello");
//    //打印出精度和纬度
//    CLLocationCoordinate2D coordinate = newLocation.coordinate;
//    NSLog(@"输出当前的精度和纬度");
//    NSLog(@"精度：%f 纬度：%f",coordinate.latitude,coordinate.longitude);
//    //停止定位
//    [locationmanager stopUpdatingLocation];
//    //计算两个位置的距离
//    float distance = [newLocation distanceFromLocation:oldLocation];
//    NSLog(@" 距离 %f",distance);
//    
//    //====位置的反编码 5.0 之后的
//    /*
//     
//     */
//    
//    geocoder = [[CLGeocoder alloc]init];
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray*placemarks,NSError* error)
//     {
//         //NSLog(@"hffjv");
//         for (CLPlacemark* place in placemarks) {
//             //NSLog(@"hffjv");
//             NSLog(@"name %@",place.name); //位置
//             NSLog(@"thoroughfare %@",place.thoroughfare);//街道
//             //子街道
//             NSLog(@"subthoroughfare %@",place.subAdministrativeArea);
//             //市
//             NSLog(@"loclitity %@",place.locality);
//             //区
//             NSLog(@"subLocality %@",place.subLocality);
//             //国家
//             NSLog(@"country %@",place.country);
//             NSLog(@"hffjv");
//         }
//         
//     }];
//}



- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 2000, 2000);
    //[mapView setRegion:viewRegion animated:YES];
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
    [_mapView setRegion:adjustedRegion animated:YES];
    
    manager.delegate = nil;
    [manager stopUpdatingLocation];
    
    MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
    geocoder.delegate = self;
    [geocoder start];
}



// 6.0 之后新增的位置调用方法

-(void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray *)locations
 {
 for (CLLocation* location in locations) {
 NSLog(@"%@",location);
 }
 //停止定位
 // [manager stopUpdatingLocation];
 
 }
 


#pragma mark MKMapViewDelegate的代理方法
//返回标注视图（大头针视图）
/*- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <mkannotation>)annotation
 {
 
 }*/

//更新当前位置调用
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    
}
//选中注释图标
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    
}
//地图的显示区域改变了调用
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    
}

//成功编码回调方法
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    
    MapLocation *annotation = [[MapLocation alloc] init];
    annotation.streetAddress = placemark.thoroughfare;
    annotation.city = placemark.locality;
    annotation.state = placemark.administrativeArea;
    annotation.zip = placemark.postalCode;
    annotation.coordinate = geocoder.coordinate;
    [_mapView addAnnotation:annotation];
    
    [annotation release];
    geocoder.delegate = nil;
    [geocoder autorelease];
    
    [self.activity stopAnimating];
    self.activity.hidden = YES;
}

//失败编码回调方法
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地理解码错误息"
                          message:@"地理代码不能识别"
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    geocoder.delegate = nil;
    [geocoder autorelease];
    
    [self.activity stopAnimating];
}


//
//MKMapViewDelegate
//
//是地图视图委托对象，本例子我们使用的方法：
//
//- mapView:viewForAnnotation:为地图设置标注时候回调方法。
//
//-mapViewDidFailLoadingMap:withError:地图加载错误时候回调方法。
//
//地图标注回调方法
#pragma mark Map View Delegate Methods
- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>) annotation {
    
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];
    if(annotationView == nil) {
        annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:@"PIN_ANNOTATION"] autorelease];
    }
    annotationView.canShowCallout = YES;
    annotationView.pinColor = MKPinAnnotationColorRed;
    annotationView.animatesDrop = YES;
    annotationView.highlighted = YES;
    annotationView.draggable = YES;
    return annotationView;
}



- (void)mapViewDidFailLoadingMap:(MKMapView *)theMapView withError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地图加载错误"
                          message:[error localizedDescription]
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

//
//与表格视图单元格处理类似，地图标注对象由于会很多，因此需要重复利用，通过
//
//dequeueReusableAnnotationViewWithIdentifier方法可以查找可重复利用的标注对象，以达到节省内存的目的。
//
//annotationView.canShowCallout = YES;指定标注上的插图，点击图钉有气泡显示。
//
//annotationView.pinColor 设置图钉的颜色。
//
//annotationView.animatesDrop动画效果。
//
//地图加载失败回调方法

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
